#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <termios.h>
#include <stdbool.h>
#include <errno.h>
#include <sys/time.h>
#include <time.h>

#include "configuration.h"

struct termios tmp, old;

/**
 * @brief   取消标准输入流对Backspace按键的回显, 即取消'\b'
 * @param   void
 * @return  void
 */ 
void setstty(void)
{

    /**
     * 得到系统termion的状态 
     */
    if(tcgetattr(STDIN_FILENO, &tmp) == -1)
    {
        printf("tcgetattr error： %s\n", strerror(errno));
        return ;
    }
    old = tmp;
    tmp.c_cc[VERASE] = '\b';

    /**
     * 设置系统termion的状态，TCSANOW表示设置完成效果立即生效 
     */
    if(tcsetattr(STDIN_FILENO, TCSANOW, &tmp) == -1)
    {
        printf("tcsetattr error： %s\n", strerror(errno));
        return ;
    }
}

/**
 * @brief   恢复标准输入流对Backspace按键的回显, 即输入'\b', 显示^H
 * @param   void
 * @return  void
 */ 
void renew(void)
{
    if(tcsetattr(STDIN_FILENO, TCSANOW, &old) == -1)
    {
        printf("tcsetattr error： %s\n", strerror(errno));
        return ;
    }
}

/* 
 * set_buffered_input() can hide input command.
 * Turn param into 'false' enabled it;
 * Turn param into 'ture' disabled it;
 */ 
void set_buffered_input(bool enable) 
{
    static bool enabled = true;
    static struct termios old;
    struct termios new;

    if (enable && !enabled) {
        /* restore the former settings */
        tcsetattr(STDIN_FILENO,TCSANOW,&old);
        /* set the new state */
        enabled = true;
    } else if (!enable && enabled) {
        /* get the terminal settings for standard input */
        tcgetattr(STDIN_FILENO,&new);
        /* we want to keep the old setting to restore them at the end */
        old = new;
        /* disable canonical mode (buffered i/o) and local echo */
        new.c_lflag &=(~ICANON & ~ECHO);
        /* set the new settings immediately */
        tcsetattr(STDIN_FILENO,TCSANOW,&new);
        /* set the new state */
        enabled = false;
    }
}
